package class3;

import common.ListNode;
import common.ListNodeUtils;

/**
 * 打印两个有序链表的公共部分
 * 1 -> 2 -> 3 -> 5 -> 7 -> 8 -> 10;
 * 3 -> 4 -> 7 -> 8 -> 11;
 * 3 -> 7 -> 8
 */
public class Code10_PrintCommonPart {
    public static void main(String[] args) {
        ListNode head1 = ListNodeUtils.getLinked(new int[]{1, 2, 3, 5, 7, 8, 10});
        ListNode head2 = ListNodeUtils.getLinked(new int[]{3, 4, 7, 8, 11});
        printCommonPart(head1,head2);
    }

    public static void printCommonPart(ListNode head1, ListNode head2) {
        if (head1 == null || head2 == null) {
            return;
        }
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        ListNode ans = null;
        ListNode tail = null;
        while (cur1 != null) {
            if (cur1.val > cur2.val) {
                cur2 = cur2.next;
            } else if (cur1.val < cur2.val) {
                cur1 = cur1.next;
            } else {
                if (ans == null) {
                    ans = new ListNode(cur1.val);
                    tail = ans;
                } else {
                    tail.next = new ListNode(cur1.val);
                    tail = tail.next;
                }
                cur1 = cur1.next;
                cur2 = cur2.next;
            }
        }
        ListNodeUtils.print(ans);
    }
}
